<template>
    <div>
        <rui-page :defines="defines" v-show="isShow">
            <br>
            <div v-show="isShow">
                <rui-query :label-width="120"
                           ref="searchFormPlan"
                           :query="queryData"
                           :query-rows="searchFormOptions"
                >
                </rui-query>
                <Row>
                    <Alert show-icon>
                        已选择 <span class="select-count">{{selectCount}}</span> 项
                        <a class="select-clear" @click="clearSelectAll">清空</a>
                    </Alert>
                </Row>
                <rui-table
                    :defineId="'discountPlanTableDefine'"
                    :fixedLeft="['action']"
                    :showIndex="false"
                    :select="true"
                    :columns="discountPlanColumns"
                    :slots="[{key:'action',slot:'action'},{key:'status',slot:'status'},{key:'discountPlanName',slot:'discountPlanName'}]"
                    @loadDatas="queryData"
                    @on-selection-change="changeSelect"
                    ref-query="searchFormPlan"
                    ref="planTable"
                >
                    <template slot="toolBar">
                        <Button @click="add" icon="md-add" type="primary">新增</Button>
                        <Button @click="effectiveAll" type="primary">有效</Button>
                        <Button @click="invalidAll" type="primary">无效</Button>
                    </template>
                    <template slot="action" slot-scope="{ row }">
                        <div>
                            <Button type="primary" size="small" v-if="row.status=='0'" @click="edit(row)">编辑</Button>
                            <Button type="error" size="small" v-if="row.status=='0'" @click="remove(row)">删除</Button>
                            <Button @click="view(row)" size="small" type="primary" v-if="row.status=='1'">查看</Button>
                            <Button @click="copy(row)" size="small" v-if="row.status=='1'" type="primary">复制</Button>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="status">
                        <div>
                            <tag v-if="row.status=='1'" color="success" size="default">有效</tag>
                            <tag v-if="row.status=='0'" color="error" size="default">无效</tag>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="discountPlanName">
                        <a @click="view(row)">
                            {{row.discountPlanName}}
                        </a>
                    </template>
                </rui-table>

                <Modal
                    v-model="isShowCopy"
                    :title="copyTitle"
                    :width="500"
                    :closable="false"
                    :mask-closable="false"
                    @keydown.enter.native="saveCopy"
                    @on-ok="saveCopy">
                    <rui-form :form-options="formOptions"
                              :label-width="150"
                              :read-only="false"
                              ref="showForm">
                    </rui-form>
                    <div slot="footer">
                        <Button size="small" @click="isShowCopy = false">取消</Button>
                        <Button type="primary" size="small" @click="saveCopy">保存</Button>
                    </div>
                </Modal>

            </div>
        </rui-page>
        <discountConfig ref="discountConfig" :param="param" :op="op" v-if="!isShow" @saveSuccess="parentReceive"/>
    </div>
</template>
<script>
    import discountPlanDefine from "./define/discount-plan-define";
    import discountPlanTableDefine from "./define/discount-plan-table-define";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        deleteById,
        getSelectDiscountShare,
        getDiscountPlanList,
        effectiveDiscountPlan,
        invalidDiscountPlan,
        copyPlan,
    } from "@/projects/afs-core-business/api/afs-product/product/discountPlan";
    import discountConfig from "./discountPlanConfig.vue";

    export default {
        components: {
            discountConfig
        },
        data() {
            return {
                locationData: [],
                isShow: true,
                isShowConfig: false,
                searchFormOptions: [
                    {
                        defineId: "defineDiscountPlan",
                        span: 6,
                        fields: ["discountNo", "discountPlanName", "discountCalculateMethod"]
                    },
                    {
                        defineId: "defineDiscountPlan",
                        span: 6,
                        fields: ["discountShareMethod", "status"],
                    },
                ],
                discountPlanColumns: [
                    'action', 'discountNo', 'discountPlanName', 'discountCalculateMethod', 'discountShareMethod',  'status'
                ],
                selectCount: 0,
                isShowCopy:false,
                copyTitle:"复制方案",
                formOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: "defineDiscountPlan", span: 24, fields: ["discountPlanName"]},
                        ]
                    }
                ],
                submitLoading: false,

                //组件传值
                param:{},
                op:null,
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineDiscountPlan",
                        fields: discountPlanDefine
                    },
                    {
                        id: "discountPlanTableDefine",
                        fields: discountPlanTableDefine
                    }
                ];
            }
        },
        mounted() {
            this.selectDiscountSourceData();
            this.refresh();
        },
        methods: {
            parentReceive() {
                this.refresh();
                this.isShow = true;
            },
            selectDiscountSourceData() {
                getSelectDiscountShare().then(res => {
                    if (res.code === "0000") {
                        this.locationData = res.data;
                    }
                });
            },
            queryData(queryData) {
                getDiscountPlanList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.planTable.updateTableData(records, total);
                    }
                });
            },
            refresh() {
                this.$refs['planTable'].reloadData();
                this.clearSelectAll();
            },
            clearSelectAll() {
                this.$refs.planTable.getTable().selectAll(false);
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            effectiveAll() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("您还未选择数据");
                    return;
                }
                if(this.check("effective")){return;}
                this.$Modal.confirm({
                    title: "确认生效",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        effectiveDiscountPlan(ids).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            invalidAll() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("您还未选择数据");
                    return;
                }
                if(this.check("invalid")){return;}
                this.$Modal.confirm({
                    title: "确认无效",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        invalidDiscountPlan(ids).then(res => {
                            if (res.code === "0000") {
                                this.refresh();
                            }
                            this.$Message.success(res.msg);
                        });
                    }
                });
            },
            check(type){
                let invalidNum = 0;
                let effectiveNum = 0;
                this.selectList.forEach((e) => {
                    if(e.status==0){//无效
                        invalidNum++;
                    }else if(e.status==1){//有效
                        effectiveNum++;
                    }
                });
                var checkResult = false;
                if("invalid"==type&&invalidNum>0){
                    this.$Message.warning("不可设置无效数据为无效！");
                    checkResult = true;
                }
                if("effective"==type&&effectiveNum>0){
                    this.$Message.warning("不可设置有效数据为有效！");
                    checkResult = true;
                }
                return checkResult;
            },
            add() {
                this.isShowConfig = true;
                this.isShow = false;
                this.op = 'add';
                this.param = null;
            },
            edit(v) {
                this.isShowConfig = true;
                this.isShow = false;
                this.op = 'edit';
                this.param = v;
            },
            view(v) {
                this.isShowConfig = true;
                this.isShow = false;
                this.op = 'view';
                this.param = v;
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除吗",
                    content: "您确认要删除这条数据?",
                    onOk: () => {
                        deleteById(v.id).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success(res.msg);
                                this.refresh();
                            }
                        });
                    }
                });
            },
            copy(row){
                this.isShowCopy = true;
                this.$refs.showForm.resetFrom();
                this.$refs.showForm.setFieldRequired('discountPlanName', true);
                this.$refs.showForm.updateFormData(deepClone(row));
            },
            saveCopy(){
                this.submitLoading = true;
                this.$refs.showForm.getForm().validate((valid) => {
                    if (valid) {
                        copyPlan(this.$refs.showForm.getFormData()).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("复制成功");
                                this.isShowCopy = false;
                                this.refresh();
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    }
                });
            },
        }
    };
</script>
